/*
 * 
 * Copyright 2010 David H Pollack
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 * 
 * 
 */

package fantasy;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.security.SecureRandom;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.exception.OAuthCommunicationException;
import oauth.signpost.exception.OAuthExpectationFailedException;
import oauth.signpost.exception.OAuthMessageSignerException;

import net.oauth.OAuthException;

import com.google.appengine.api.urlfetch.HTTPHeader;
import com.google.appengine.api.urlfetch.HTTPMethod;
import com.google.appengine.api.urlfetch.HTTPRequest;
import com.google.appengine.api.urlfetch.HTTPResponse;
import com.google.appengine.api.urlfetch.URLFetchService;
import com.google.appengine.api.urlfetch.URLFetchServiceFactory;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gdata.client.authn.oauth.OAuthUtil;
import com.simpleyql.Api;
import com.simpleyql.ApiFactory;
import com.simpleyql.QueryResult;


@SuppressWarnings("unused")
public class TestServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6314522171071524517L;

	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
		throws IOException {

        // Stuff to get baseurl
		Properties props = new Properties();
        props.load(this.getClass().getClassLoader().getResourceAsStream("fantasy.properties"));
        String baseurl = props.getProperty("application.baseurl");

        // Set to expire far in the past.
		resp.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
		// Set standard HTTP/1.1 no-cache headers.
		resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
		resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
		// Set standard HTTP/1.0 no-cache header.
		resp.setHeader("Pragma", "no-cache");
		
		String yql2 = URLDecoder.decode(req.getParameter("url"), "US-ASCII");
		
		resp.setContentType("text/html");
		resp.getWriter().println("Test 2:\n");

		UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

		PersistenceManager pm = PMF.get().getPersistenceManager();

	    Query query = pm.newQuery(UserTable.class);
	    query.setFilter("userkey == nickNameParam");
	    query.declareParameters("String nickNameParam");
	    
	    UserTable a = null;
	    
		resp.getWriter().println("Welcome: " + user.getNickname());
	    
	    try {
	    	List<UserTable> uquery = (List<UserTable>) query.execute(user.getNickname());
	    	if (!uquery.isEmpty()) {
			    a = uquery.get(0);
			    resp.getWriter().println("Get Index Test");
		    } else {
		    	resp.getWriter().println("User Not Found");
		    }
	    } finally {
	        query.closeAll();
	    }
	    
		Api api = ApiFactory.getApiInstance(
	            "dj0yJmk9NGVDelJyN2MzWW5zJmQ9WVdrOVRFcGFaalZrTkdrbWNHbzlNak16TVRFNE5qWXkmcz1jb25zdW1lcnNlY3JldCZ4PTM2",
	            "91b08a397dc663f4372f6a4fa31e693f6ab7bf54",
	            baseurl + "/simpleyqlcallback/",
	            false, null);
		QueryResult qr = null;
		
		/* Example URLs
		 * 
		 * Get All Leagues Settings for the logged in user
		 * http://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;game_keys=mlb/leagues/settings
		 * 
		 * Get All Leagues Settings AND Standings for the logged in user
		 * http://fantasysports.yahooapis.com/fantasy/v2/users;use_login=1/games;game_keys=mlb/leagues;out=settings,standings
		 *
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 * 
		 */
		
		
		String yql = (yql2 == null)? "http://social.yahooapis.com/v1/me/guid" : yql2;

		try {
			qr = api.query2(yql, a.getAuthdata());
		} catch (OAuthException e) {
			log("Error posting to Y!:", e);
			return;
		} catch (RuntimeException e) {
			if (e.getMessage().equals("Unable to complete the HTTP request")) {
				if (e.getCause().getMessage()
						.contains("Timeout while fetching")) {
					log("Unable to complete Yahoo! query", e);
				} else {
					log("Error posting to Y!:", e);
					return;
				}
			} else {
				throw e;
			}
		}

		resp.getWriter().println(qr.getText());

		// Update token, if needed (for future requests)
	    if (qr != null && !qr.getAuthdata().equals(a.getAuthdata())) {
	    	a.setAuthdata(qr.getAuthdata());
	    	try {
	    		pm.makePersistent(a);
	    	} finally {
	    		pm.close();
	    	}
	    }
	    
	    /*
	    
	    URL newUrl = new URL(yql2);
	    URLFetchService fetcher = URLFetchServiceFactory.getURLFetchService();
	    HTTPRequest request = new HTTPRequest(newUrl, HTTPMethod.GET);
	    HttpURLConnection request2;

	    String nonce = OAuthUtil.getNonce();
	    
	    String timestamp = OAuthUtil.getTimestamp();
	    
	    String yahoo_token = "A=PEiL.8We7xwrmUdOb0yg_cVEokL773NxNFjho2m8Am0K6sg3Al4iaTZtZHc.bmbVdujwpXPx2BVZrVGifOgqpJ1hfaFc7A4v6koccT74W6GLlr1_tKv7babXSQdTn74wEggpkYzPJ5bCKUurQ2w74URO_WqPghRVeIftAEcHusHyewJ.49d3492QoBd.nIx4H8jLNuHZ2FlXKaJSFFbSlA0V4aAMj_OP9wrqYqEJd39Y.9tOqjtpQ2e0YNNVM1jAycRJt0..vf0h1Jb6OD_muFBwPI0nZSWRYe6BwmPixRUYJqsui7fd7cX1k9nAyN1Y4Aoa.iSU4ignYiDvEw8Ne98xrfTWHlIuP6y4u8W1HuTlkbCep_5wllkc67tyNb7uMUMmPRd7nQl3LJcW.DxvJJ9zVcMlYd.nFrEap3UoipB9S8Uf31rftAD60GvtrePgM_SVFubBvH7qb1e1jWIJ46OyiKAuK1h8aBwgB4POgGkiH30GxNWr7bs3MVE.f8rm4w0w9inbKJke5HePm2sSISNNWGeKln5s.eIEpKfA2zTTqQ0qXsMp9eNvCMArx3kA5U9xmXSg1_XGK023EEMTjGRcYIh6Oh_4z3yYt1OH_zI1eo1DZZC7mkQ1MJ.qyQT_JaEKJWomas60QQ_jPPdsfIZhAN4zIk2CqAtk6rZjlrY61XiCjQYw2gmv7wCA2MrVWViwFsNYTi1.FekRW4I-";
	    
	    String yahoo_token_secret = "e4a061183cf6c2e00eb794f39e514ff7f274f83d";
	    
	    String yahoo_consumer_key = "dj0yJmk9NGVDelJyN2MzWW5zJmQ9WVdrOVRFcGFaalZrTkdrbWNHbzlNak16TVRFNE5qWXkmcz1jb25zdW1lcnNlY3JldCZ4PTM2";
	    
	    String yahoo_consumer_secret = "91b08a397dc663f4372f6a4fa31e693f6ab7bf54";
	    
	    Map<String, String> requestParameters = new HashMap<String, String>();
	    
        OAuthConsumer consumer = new CommonsHttpOAuthConsumer(yahoo_consumer_key,yahoo_consumer_secret);
        consumer.setTokenWithSecret(yahoo_token, yahoo_token_secret);
        
        
        
        try {
			consumer.sign(request);
		} catch (OAuthMessageSignerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthExpectationFailedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OAuthCommunicationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		Future<HTTPResponse> future = fetcher.fetchAsync(request);
		
        HTTPResponse response;
		try {
			response = future.get();
	        byte[] content = response.getContent();
			log(new String(content));
	        URL finalUrl = response.getFinalUrl();
	        int responseCode = response.getResponseCode();
	        List<HTTPHeader> headers = response.getHeaders();

	        for(HTTPHeader header : headers) {
	        	String headerName = header.getName();
	        	String headerValue = header.getValue();
	        }

		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ExecutionException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
        
        */
        

	    
	    
	    // A=PEiL.8We7xwrmUdOb0yg_cVEokL773NxNFjho2m8Am0K6sg3Al4iaTZtZHc.bmbVdujwpXPx2BVZrVGifOgqpJ1hfaFc7A4v6koccT74W6GLlr1_tKv7babXSQdTn74wEggpkYzPJ5bCKUurQ2w74URO_WqPghRVeIftAEcHusHyewJ.49d3492QoBd.nIx4H8jLNuHZ2FlXKaJSFFbSlA0V4aAMj_OP9wrqYqEJd39Y.9tOqjtpQ2e0YNNVM1jAycRJt0..vf0h1Jb6OD_muFBwPI0nZSWRYe6BwmPixRUYJqsui7fd7cX1k9nAyN1Y4Aoa.iSU4ignYiDvEw8Ne98xrfTWHlIuP6y4u8W1HuTlkbCep_5wllkc67tyNb7uMUMmPRd7nQl3LJcW.DxvJJ9zVcMlYd.nFrEap3UoipB9S8Uf31rftAD60GvtrePgM_SVFubBvH7qb1e1jWIJ46OyiKAuK1h8aBwgB4POgGkiH30GxNWr7bs3MVE.f8rm4w0w9inbKJke5HePm2sSISNNWGeKln5s.eIEpKfA2zTTqQ0qXsMp9eNvCMArx3kA5U9xmXSg1_XGK023EEMTjGRcYIh6Oh_4z3yYt1OH_zI1eo1DZZC7mkQ1MJ.qyQT_JaEKJWomas60QQ_jPPdsfIZhAN4zIk2CqAtk6rZjlrY61XiCjQYw2gmv7wCA2MrVWViwFsNYTi1.FekRW4I-
	    // &
	    // e4a061183cf6c2e00eb794f39e514ff7f274f83d
	    // &
	    // AL9qRkyVMviXrBdxKvAvBHr9FTPFBjt_sClrseCaFsbIwrQc3jdd 
	}
}
